package com.sunny.ynhz.ui.patrol.problems.draft;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.foamtrace.photopicker.PhotoPickerActivity;
import com.google.gson.Gson;
import com.sunny.ynhz.R;
import com.sunny.ynhz.adapter.ImageAdapter;
import com.sunny.ynhz.adapter.ProblemTypeAdapter;
import com.sunny.ynhz.api.ApiService;
import com.sunny.ynhz.api.HttpManager;
import com.sunny.ynhz.api.subscriber.ApiSubscriber;
import com.sunny.ynhz.api.upload.DefaultProgressListener;
import com.sunny.ynhz.api.upload.RetrofitUtil;
import com.sunny.ynhz.api.upload.UploadFileRequestBody;
import com.sunny.ynhz.bean.ProBean;
import com.sunny.ynhz.bean.ResultImageBean;
import com.sunny.ynhz.bean.UploadProblemBean;
import com.sunny.ynhz.db.RealmUtils;
import com.sunny.ynhz.model.IProblemTypeResultView;
import com.sunny.ynhz.model.ProblemTypeModel;
import com.sunny.ynhz.ui.base.AppBaseTranslationTitleBarActivity;
import com.sunny.ynhz.ui.patrol.problems.ChooseRiverActivity2;
import com.sunny.ynhz.ui.patrol.problems.OfficeAdminActivity2;
import com.sunny.ynhz.ui.patrol.problems.PositionMapSelectActivity;
import com.sunny.ynhz.ui.report.ChooseRiverActivityNative;
import com.sunny.ynhz.ui.report.ChooseSubmitForObjectActivityNative;
import com.sunny.ynhz.utils.GridSpacingItemDecoration;
import com.sunny.ynhz.utils.PictureUtil;
import com.sunny.ynhz.utils.SPUtil;
import com.sunny.ynhz.utils.ShowUtils;
import com.sunny.ynhz.utils.ToastUtils;
import com.sunny.ynhz.utils.TypeAndStatusUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.realm.Realm;
import io.realm.RealmResults;
import okhttp3.RequestBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by luao on 2017/7/20.
 */

public class ProblemDraftDetailActivity extends AppBaseTranslationTitleBarActivity implements CompoundButton.OnCheckedChangeListener, IProblemTypeResultView {

    @BindView(R.id.problem_detail)
    TextView problemDetail;
    @BindView(R.id.image_recycle)
    RecyclerView imageRecycle;
    @BindView(R.id.problem_addr)
    TextView problemAddr;
    @BindView(R.id.problem_type)
    TextView problemType;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.problem_draft_del)
    TextView problemDraftDel;
    @BindView(R.id.isNativeBox)
    CheckBox isNativeBox;
    @BindView(R.id.choose_river)
    TextView chooseRiver;
    @BindView(R.id.report_obj)
    TextView ReportObjTv;
    private ImageAdapter imageAdapter;
    private LinkedList dataBeenList;
    private Intent intent;
    private Gson gson;
    private ProBean dataBean;
    private String tempImagePathString = "";
    private String officeAdmin = "";
    private String riverId = "";
    private String reachId = "";
    private ArrayList<String> stringArrayListExtra;
    private Activity activity;
    private Realm mRealm;
    private ArrayList<String> imagePath;
    private RealmResults<ProBean> probelmList;
    private BottomSheetDialog bottomSheetDialog;
    private ListView listView;
    List<String> mList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other_problem_draft_details);
        ProblemTypeModel problemTypeModel = new ProblemTypeModel(this, this);
        problemTypeModel.getProblemTypeData();
        ButterKnife.bind(this);
        activity = this;
        intent = getIntent();
        mRealm = RealmUtils.getDeleteRealm();
        probelmList = mRealm
                .where(ProBean.class)
                .equalTo("id", getIntent().getStringExtra("id"))
                .findAll();
        //如果不copy无法操作
        dataBean = probelmList.get(0);
        isNativeBox.setOnCheckedChangeListener(this);
        problemDetail.setText(dataBean.getDescribe());
        problemAddr.setText(dataBean.getPosition());
        problemType.setText(TypeAndStatusUtil.getProblemTpye().get(dataBean.getType()));
        time.setText(dataBean.getTime());
        if (dataBean.getNativeprocessing().equals("0")) {
            isNativeBox.setChecked(false);
        } else if (dataBean.getNativeprocessing().equals("1")) {
            isNativeBox.setChecked(true);
        }
        imagePath = new ArrayList<>();
        if (dataBean.getPicture() != null) {
            imagePath.addAll(Arrays.asList(dataBean.getPicture().split(";")));
        }
        if (TextUtils.isEmpty(dataBean.getSectionName())) {
            chooseRiver.setText("请选择河道");
        } else {
            chooseRiver.setText(dataBean.getSectionName());
        }
        riverId = dataBean.getSectionId();
        reachId = dataBean.getReachId();


        officeAdmin = dataBean.getCuurUserId();
        String officeAdminName = dataBean.getCuurName();

        if (TextUtils.isEmpty(officeAdmin)) {
            ReportObjTv.setText("请选择提交对象");
        } else {
            ReportObjTv.setText(officeAdminName);
        }

        imageRecycle.setLayoutManager(new GridLayoutManager(this, 3));
        imageRecycle.addItemDecoration(new GridSpacingItemDecoration(3, 50, false));
        imageRecycle.setItemAnimator(new DefaultItemAnimator());
        imageAdapter = new ImageAdapter(this, imagePath);
        imageRecycle.setAdapter(imageAdapter);
        bottomSheetDialog = new BottomSheetDialog(this);
        View view1 = LayoutInflater.from(this).inflate(R.layout.lv_problem_type, null);
        listView = view1.findViewById(R.id.lv_problem);
        ProblemTypeAdapter problemTypeAdapter = new ProblemTypeAdapter(this, mList);
        listView.setAdapter(problemTypeAdapter);
        bottomSheetDialog.setContentView(view1);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                bottomSheetDialog.dismiss();
                String key = mList.get(i);
                if (TypeAndStatusUtil.getProblemTpye().get(key) != null) {
                    problemType.setText(TypeAndStatusUtil.getProblemTpye().get(key));
                    mRealm.executeTransaction(new Realm.Transaction() {
                        @Override
                        public void execute(Realm realm) {
                            dataBean.setType(key);
                        }
                    });

                }
            }
        });

    }

    /**
     * 删除问题
     */
    private void delete() {
        mRealm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                dataBean.deleteFromRealm();
                finish();

            }
        });
    }

    @OnClick({R.id.problem_draft_del, R.id.patrol_problem_upload, R.id.problem_addr, R.id.choose_river, R.id.report_obj, R.id.problem_type})
    public void onClick(View view) {
        if (view.getId() == R.id.problem_draft_del) {
            delete();
        } else if (view.getId() == R.id.patrol_problem_upload) {
            if (chooseRiver.getText().equals("请选择河道")) {
                Toast.makeText(this, "请选择河道", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!isNativeBox.isChecked()) {
                if (officeAdmin.equals("")) {
                    Toast.makeText(this, "请选择提交对象", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            if (imagePath.size() == 0) {
                Toast.makeText(this, "请至少上传一张图片", Toast.LENGTH_LONG).show();
                return;
            }
            uploadProblem();
        } else if (view.getId() == R.id.problem_addr) {
            Intent intent = new Intent(this, PositionMapSelectActivity.class);
            intent.putExtra("position", dataBean.getPosition());
            intent.putExtra("lttd", dataBean.getLttd());
            intent.putExtra("lgtd", dataBean.getLgtd());
            startActivityForResult(intent, 200);
        } else if (view.getId() == R.id.report_obj) {
            Intent intent = new Intent(this, ChooseSubmitForObjectActivityNative.class);
            startActivityForResult(intent, 500);
        } else if (view.getId() == R.id.choose_river) {
            Intent intent = new Intent(this, ChooseRiverActivityNative.class);
            startActivityForResult(intent, 600);
        } else if (view.getId() == R.id.problem_type) {
            bottomSheetDialog.show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        if (requestCode == 0 && data != null) {
            stringArrayListExtra = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
            if (stringArrayListExtra != null) {
                imagePath.clear();
                imagePath.addAll(stringArrayListExtra);
                imageAdapter.notifyDataSetChanged();
            }
        }
        if (resultCode == 200 && data != null) {
            mRealm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    dataBean.setLttd(data.getDoubleExtra("lttd", 0.0));
                    dataBean.setLgtd(data.getDoubleExtra("lgtd", 0.0));
                    dataBean.setPosition(data.getStringExtra("position"));
                    problemAddr.setText(data.getStringExtra("position"));
                }
            });
        } else if (resultCode == 300 && data != null) {
            ReportObjTv.setText(data.getStringExtra("reportObj"));
            officeAdmin = data.getStringExtra("officeAdmin");
        } else if (resultCode == 400 && data != null) {
            chooseRiver.setText(data.getStringExtra("riverNmae"));
            riverId = data.getStringExtra("riverId");
        } else if (resultCode == 500 && data != null) {
            officeAdmin = data.getStringExtra("id");
            ReportObjTv.setText(data.getStringExtra("name"));
        } else if (resultCode == 600 && data != null) {
            chooseRiver.setText(data.getStringExtra("name"));
            riverId = data.getStringExtra("id");
            reachId = data.getStringExtra("reachId");
        }

    }

    /**
     * 上传问题
     */
    public void uploadProblem() {
        if (isNativeBox.isChecked()) {
            officeAdmin = null;
        }
        if (imagePath.size() == 0) {
            ShowUtils.inItPopwin(ProblemDraftDetailActivity.this, "请等待");
            uploadProblemToHttp();
        } else {
            final Handler mHandler2 = new Handler() {
                public void handleMessage(Message msg) {
//                    Toast.makeText(activity, msg.obj.toString(), Toast.LENGTH_LONG).show();
                    ArrayList<String> filePath = (ArrayList<String>) msg.obj;
                    ArrayList<String> clonearr = (ArrayList<String>) filePath.clone();
                    ShowUtils.closePopwindow();
                    uploadFile(clonearr);
                    super.handleMessage(msg);
                }
            };
            ShowUtils.inItPopwin(activity, "正在压缩图片");
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    ArrayList<String> arrayList = new ArrayList<>();

                    for (int i = 0; i < imagePath.size(); i++) {
                        Bitmap bitmap = PictureUtil.getSmallBitmap(imagePath.get(i));
                        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                        Date date = new Date(System.currentTimeMillis());
                        String filename = format.format(date);
                        File file = PictureUtil.compressImage(bitmap, filename + i);
                        arrayList.add(file.getPath());
                    }

                    // TODO Auto-generated method stub
                    Message message = new Message();
                    message.obj = arrayList;
                    mHandler2.sendMessage(message);
                }
            });
            thread.start();
        }
    }


    /**
     * 上报问题
     */
    private void uploadProblemToHttp() {
        String patrolId = SPUtil.get("patrolId", "null").toString();
        mRealm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                if (isNativeBox.isChecked()) {
                    dataBean.setNativeprocessing("1");
                } else {
                    dataBean.setNativeprocessing("0");
                }

            }
        });
        HttpManager.getInstance()
                .uploadProblem(dataBean.getType(), dataBean.getTime(), dataBean.getUserId(), dataBean.getNativeprocessing(), dataBean.getLttd(), dataBean.getLgtd(),
                        dataBean.getPosition(), dataBean.getDescribe(), dataBean.getAddvcd(), patrolId, tempImagePathString, null, "0", "2",
                        officeAdmin, riverId, reachId)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ApiSubscriber(this, new ApiSubscriber.HttpOnResultListener<UploadProblemBean>() {
                    @Override
                    public void onNext(UploadProblemBean jsonObject) {
                        ShowUtils.closePopwindow();
                        ToastUtils.SingleToastUtil(ProblemDraftDetailActivity.this, "提交成功");
                        delete();
                    }

                    @Override
                    public void onCompleted() {
                        ShowUtils.closePopwindow();
                    }

                    @Override
                    public void onstart() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        ShowUtils.closePopwindow();
                    }
                }));
    }

    private Handler mHandler = new Handler() {
        /**
         * what是文件上传百分比
         *
         * @param msg
         */
        @Override
        public void handleMessage(Message msg) {
            switch (msg.arg1) {
                case 1:
                    if (msg.what > 0) {

                    }
                    break;
            }
        }
    };


    /**
     * 文件上传，一个接一个
     *
     * @param filePath 文件路径数组
     */
    public void uploadFile(List<String> filePath) {
        File cutFile = null;
        if (filePath.size() > 0) {
            cutFile = new File(filePath.get(0));
        }

        if (cutFile != null) {
            ApiService uploadFileService = RetrofitUtil.createService(ApiService.class);
            Map<String, String> optionMap = new HashMap<>();
            optionMap.put("name", cutFile.getName());
            optionMap.put("path", "path");

            Map<String, RequestBody> requestBodyMap = new HashMap<>();
            UploadFileRequestBody fileRequestBody = new UploadFileRequestBody(cutFile, new DefaultProgressListener(mHandler, 1));
            requestBodyMap.put("file\"; filename=\"" + cutFile.getName(), fileRequestBody);


            final List<String> finalFilePath = filePath;
            uploadFileService.uploadFileInfo(optionMap, requestBodyMap).
                    subscribeOn(Schedulers.io()).
                    observeOn(AndroidSchedulers.mainThread()).
                    subscribe(new Subscriber<ResultImageBean>() {
                        @Override
                        public void onStart() {
                            super.onStart();
                            loadOutStart();
                        }

                        @Override
                        public void onCompleted() {
                            loadOnAfter();
                        }

                        @Override
                        public void onError(Throwable e) {
                            loadOnAfter();
                            Log.e("TAG", e.getMessage());
                        }

                        @Override
                        public void onNext(ResultImageBean s) {
                            tempImagePathString = tempImagePathString + s.getNewPath() + ";";
                            finalFilePath.remove(0);
                            if (finalFilePath.size() == 0) {
                                uploadProblemToHttp();
                            } else {
                                uploadFile(finalFilePath);
                            }

                            loadOnAfter();
                        }

                    });
        }


    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        if (compoundButton.equals(isNativeBox)) {
            if (b) {
                //本级处理
                ReportObjTv.setClickable(false);
                ReportObjTv.setTextColor(Color.GRAY);
            } else {
                //不是本级处理
                ReportObjTv.setClickable(true);
                ReportObjTv.setTextColor(Color.BLACK);

            }
        }

    }

    @Override
    public void onSuccess(Object o) {

    }

    @Override
    public void onCache() {

    }

    @Override
    public void onFail() {

    }

    @Override
    public void onStartLoad() {

    }
}
